package vip.liux.backend.infrastructure.excel.handler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import vip.liux.backend.infrastructure.excel.ExportContext;
import vip.liux.backend.infrastructure.excel.exception.ExcelException;

import java.io.OutputStream;
import java.util.List;
import java.util.Objects;

/**
 * @author JiaDu
 * @version 1.0.0
 * @since 2023/10/12
 */
public class ManySheetWriteHandler extends AbstractSheetWriteHandler {

    /**
     * 当且仅当List不为空且List中的元素也是List 才返回true
     *
     * @param obj 返回对象
     * @return boolean
     */
    @Override
    public boolean support(Object obj) {
        if (obj instanceof List<?> objList) {
            return !objList.isEmpty() && objList.get(0) instanceof List<?>;
        } else {
            throw new ExcelException("@ExportExcel 返回值必须为List类型");
        }
    }

    /**
     * 写入数据到Excel文件
     *
     * @param obj           数据对象
     * @param outputStream  输出流
     * @param exportContext 导出上下文配置
     */
    @Override
    public void write(Object obj, OutputStream outputStream, ExportContext exportContext) {
        Assert.isInstanceOf(List.class, obj, "导出数据必须为List类型");
        Assert.notNull(outputStream, "输出流不能为空");
        Assert.notNull(exportContext, "导出上下文��置不能为空");

        List<?> objList = (List<?>) obj;
        ExcelWriter excelWriter = getExcelWriter(outputStream, exportContext);

        boolean useTemplate = StringUtils.isNotBlank(exportContext.getLocalTemplate())
                              || Objects.nonNull(exportContext.getRemoteTemplate());

        List<ExportContext.Sheet> sheets = exportContext.getSheets();
        Assert.isTrue(objList.size() == sheets.size(), "数据列表与Sheet配置数量不匹配");

        WriteSheet sheet;
        for (int i = 0; i < sheets.size(); i++) {
            List<?> dataList = (List<?>) objList.get(i);

            if (CollectionUtils.isEmpty(dataList)) {
                sheet = EasyExcel.writerSheet(sheets.get(i).getSheetName()).build();
            } else {
                Class<?> dataClass = dataList.get(0).getClass();
                sheet = this.sheet(sheets.get(i), dataClass, useTemplate, exportContext.getHeadGenerateClass());
            }

            if (exportContext.isFill()) {
                excelWriter.fill(dataList, sheet);
            } else {
                excelWriter.write(dataList, sheet);
            }
        }
        excelWriter.finish();
    }

}
